<template>
    <div class="nav-header">
      <div class="nav-left">
        <span class="logo">上清华后台管理</span>
      </div>
      <div class="nav-right">
        <span class="user-nickname">{{ nickname }}</span>
        <el-dropdown trigger="hover" @command="handleCommand">
          <div class="avatar-container">
            <img :src="avatar" alt="User Avatar" class="user-avatar" />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="logout">
                <i class="el-icon-switch-button"></i> 退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </template>
  
  <script setup lang="js">
  import { ref, onMounted } from "vue";
  import { ElMessage } from "element-plus";
  import { useRouter } from "vue-router";
  
  let avatar = ref("");
  let nickname = ref("");
  const router = useRouter();
  
  const handleCommand = (command) => {
    if (command === "logout") {
      ElMessage.success("已退出登录！");
      localStorage.clear(); // 清除本地存储
      router.push("/login"); // 跳转到登录页
    }
  };
  
  onMounted(() => {
    avatar.value = localStorage.getItem("avatar");
    nickname.value = localStorage.getItem("nickname") || "用户"; // 默认昵称为 "用户"
    if (!avatar.value) {
      router.push("/login");
    }
  });
  </script>
  
  <style scoped lang="less">
  .nav-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 60px;
    background-color: #ffffff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  
    .nav-left {
      .logo {
        font-size: 18px;
        font-weight: bold;
        color: #333;
      }
    }
  
    .nav-right {
      display: flex;
      align-items: center;
      gap: 10px; /* 添加间距 */
      
      .user-nickname {
        font-size: 16px;
        color: #333;
      }
  
      .avatar-container {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        overflow: hidden;
        cursor: pointer;
  
        .user-avatar {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
    }
  }
  </style>
  